

package br.com.serialmanager.model.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import br.com.serialmanager.util.DatabaseHelper;
import br.com.serialmanager.util.DatabaseHelper.Mascara;

public class MascaraDao {

	private DatabaseHelper helper;
	private SQLiteDatabase db;
	
	public MascaraDao(Context context) {
		this.helper = new DatabaseHelper(context);
	}
	
	private SQLiteDatabase getDb() {
		if (this.db == null) {
			this.db = this.helper.getWritableDatabase();
		}
		return this.db;
	}

	public List<Map<String, Object>> listarMascaras() {
		List<Map<String, Object>> lista = new ArrayList<Map<String, Object>>();
		Cursor cursor = this.getDb().query(Mascara.TABELA, Mascara.COLUNAS, null, null, null, null, Mascara._ID);
		if (cursor.moveToFirst()) {
			do {
				Map<String, Object> item = new HashMap<String, Object>();
				item.put("masc_id", cursor.getInt(0));
				item.put("masc_formato", cursor.getString(1));
				lista.add(item);
			} while (cursor.moveToNext());
		}
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
		return lista;
	}
	
	public boolean salvarMascara(br.com.serialmanager.model.bean.Mascara mascara) {
		long resultado;
		ContentValues values = new ContentValues();
		values.put(Mascara.FORMATO, mascara.getFormato());
		if (mascara.getId() != null) {
			values.put(Mascara._ID, mascara.getId());
			resultado = this.getDb().update(Mascara.TABELA, values, "masc_id = ?", new String[]{mascara.getId().toString()});
		} else {
			resultado = this.getDb().insert(Mascara.TABELA, null, values);
		}
		return resultado != -1 ? true : false;
	}

	public br.com.serialmanager.model.bean.Mascara carregarPorId(String idMascara) {
		// TODO Auto-generated method stub
		br.com.serialmanager.model.bean.Mascara masc = null;
		Cursor cursor = this.getDb().query(Mascara.TABELA, Mascara.COLUNAS, "masc_id = ?", new String[]{idMascara}, null, null, null);
		if (cursor.moveToFirst()) {
			masc = new br.com.serialmanager.model.bean.Mascara(cursor.getInt(0), cursor.getString(1));
		}
		return masc;
	}
	
	public br.com.serialmanager.model.bean.Mascara carregarPorFormato(String formato) {
		br.com.serialmanager.model.bean.Mascara masc = null;
		Cursor cursor = this.getDb().query(Mascara.TABELA, Mascara.COLUNAS, "masc_formato = ?", new String[]{formato}, null, null, null);
		if (cursor.moveToFirst()) {
			masc = new br.com.serialmanager.model.bean.Mascara(cursor.getInt(0), cursor.getString(1));
		}
		return masc;
	}
	
	public boolean apagarMascara(String id) {
		long resultado = this.getDb().delete(Mascara.TABELA, "masc_id = ?", new String[]{id});
		return resultado > 0 ? true : false;
	}
}
